package com.googlecode.mapperdao.drivers

import com.googlecode.mapperdao._
import com.googlecode.mapperdao.jdbc.{Batch, Jdbc}
import com.googlecode.mapperdao.queries.v2.QueryInfo
import com.googlecode.mapperdao.schema.{ColumnBase, PK, SimpleColumn}
import com.googlecode.mapperdao.sqlbuilder.{SqlBuilder, SqlSelectBuilder}

/**
 * @author kostantinos.kougios
 *
 *         23 Nov 2011
 */
class H2(override val jdbc: Jdbc, val typeRegistry: TypeRegistry, val typeManager: TypeManager) extends Driver
{

	def batchStrategy(autogenerated: Boolean) = if (autogenerated) Batch.NoBatch else Batch.WithBatch

	val escapeNamesStrategy = new EscapeNamesStrategy
	{
		val invalidColumnNames = Set("select", "where", "group")
		val invalidTableNames = Set("select", "where", "group", "values")

		override def escapeColumnNames(name: String) = if (invalidColumnNames.contains(name.toLowerCase)) '"' + name + '"'; else name

		override def escapeTableNames(name: String) = if (invalidTableNames.contains(name.toLowerCase)) '"' + name + '"'; else name
	}
	val sqlBuilder = new SqlBuilder(this, escapeNamesStrategy)

	override protected[mapperdao] def getAutoGenerated(
		m: java.util.Map[String, Object],
		column: SimpleColumn
		) =
		m.get("SCOPE_IDENTITY()")

	override protected def sequenceSelectNextSql(sequenceColumn: ColumnBase): String = sequenceColumn match {
		case PK(_, columnName, true, sequence, _) => "NEXTVAL('%s')".format(sequence.get)
	}

	override def endOfQuery[ID, PC <: Persisted, T](q: SqlSelectBuilder, queryConfig: QueryConfig, qe: QueryInfo[ID, T]) = {
		queryConfig.limit.foreach(l => q.appendSql("limit " + l))
		queryConfig.offset.foreach {
			o =>
				if (!queryConfig.limit.isDefined) q.appendSql("limit -1")
				q.appendSql("offset " + o)
		}
		q
	}

	override def toString = "H2"
}